<template>
  <div class="order-detail-container">
    <van-nav-bar title="订单详情" left-arrow @click-left="$router.back()" />

    <div class="order-status">
      <!-- <van-steps :active="0" active-color="#07c160">
        <van-step>等待报价</van-step>
        <van-step>选择师傅</van-step>
        <van-step>服务中</van-step>
        <van-step>已完成</van-step>
      </van-steps> -->

      <div class="status-tip">
        <p class="title">{{ order.status }}</p>
        <div v-if="order.status === '已取消'" style="font-size: 12px; color: #999; margin-top: 4px;">
      {{ order.description }}
    </div>
        <!-- <p class="desc">师傅预计在5-30分钟内报价，报价后请尽快选择师傅为您提供服务</p> -->
      </div>

      <!-- <van-count-down :time="time" class="countdown">
        <template #default="timeData">
          <span class="block">距离报价截止还剩</span>
          <span class="time">{{ `${timeData.hours}时${timeData.minutes}分${timeData.seconds}秒` }}</span>
        </template>
      </van-count-down> -->
    </div>

    <van-cell-group class="order-info">
      <!-- <van-cell title="订单编号" :value="orderDetail.orderId" /> -->
      <van-cell title="订单编号" :value="order.orderId" />
      <van-cell title="下单时间" :value="formatWithDayjs(order.createTime)" />
      <van-cell title="期望上门时间" :value="orderDetail[0].serviceTime" />
      <van-cell title="服务地址">
        <template #default>
          <div class="custom-address-cell">
            <span>{{ orderDetail.contactName }}</span> <span>{{ orderDetail.contactPhone }}</span>
            <div class="address">{{ address.addresss }}</div>
          </div>
        </template>
      </van-cell>
      <template #extra>
        <van-icon name="copy" @click="copyOrderNumber" />
      </template>
    </van-cell-group>

    <van-collapse v-model="activeCollapse" class="service-detail">
      <van-collapse-item :title="category.categories.categoryName" :value="`x${orderDetail[0].itemQuantity}`">
        <div class="service-item">
          <van-cell title="服务类型" :value="service.services.serviceName" class="custom-cell" />
          <!-- <van-cell v-if="orderDetail[0].itemImages" title="图片" :value="orderDetail[0].itemImages" class="custom-cell" /> -->
        </div>
      </van-collapse-item>
    </van-collapse>

    <div class="guarantee-card">
      <div class="header">
        <span>保障卡</span>
        <span class="detail-link">了解详情 ></span>
      </div>
      <p class="tip">支付订单后即可享受四大保障</p>
    </div>

    <div class="assistant-card">
      <div class="left">
        <div class="text">
          <p class="title">添加小管家</p>
          <p class="desc">享专属1V1服务</p>
        </div>
      </div>
      <div class="right">
        <van-tag plain type="primary">协助找师傅</van-tag>
        <van-tag plain type="primary">订单咨询</van-tag>
        <van-tag plain type="primary">服务质保</van-tag>
      </div>
    </div>

    <!-- 底部操作按钮 -->
<div class="action-buttons">
  <div class="icon-with-text">
    <van-icon name="service" size="15" color="gray" />
    <span class="text">咨询</span>
  </div>
  
  <!-- 仅当状态是 "已支付" 或 "待支付" 时显示按钮 -->
  <!-- <template v-if="order.value.status === '已支付' || order.value.status === '待支付'"> -->
  <template v-if="order.status === '已支付' || order.status === '待支付'">
    <div class="button-group">

      <van-button 
        plain 
        hairline 
        type="default" 
        size="small" 
        class="cancel-btn" 
        @click="handleCancel(orderId)"
      >
        取消订单
      </van-button>

      <van-button 
        plain 
        hairline 
        type="primary" 
        size="small" 
        class="modify-btn" 
        @click="handleModify(orderId)"
      >
        修改订单
      </van-button>

    </div>
  </template>
</div>

  </div>
</template>

<script setup>
import { onMounted, ref, computed, unref } from 'vue';
import { showToast } from 'vant';
import { useRoute, useRouter } from 'vue-router';
import { getFullOrderDetail, getOrdersByUserWithService,getDetailsByOrderId, findOrderByOrderId, getServiceById, getCategoryById, getAddressByAddressId } from '@/api/index';
import dayjs from 'dayjs';

const formatWithDayjs = (isoString) => {
  return isoString ? dayjs(isoString).format('YYYY-MM-DD HH:mm') : '未知时间';
};


const route = useRoute();
const router = useRouter();
const orderId = ref(null);
const order = ref([]);
const address = ref([]);

const service = ref({
  services: {
    serviceId: null,
    categoryId: '',
    serviceName: '',
    price: null,
    description: ''
  }
});
const category = ref({
  categories: {
    categoryId: null,
    categoryName: '',
  }
});

const orderDetail = ref([
  {
    addressId: null,
    categoryId: null,
    contactName: '',
    contactPhone: '',
    detailId: null,
    itemImages: '',
    itemQuantity: 0,
    orderId: null,
    serviceId: null,
    serviceTime: null,
    specialRequirements: '',
    updateTime: ''
  }
]);

const activeCollapse = ref(['1']);
const time = ref(24 * 60 * 60 * 1000); // 24小时倒计时

const copyOrderNumber = () => {
  navigator.clipboard.writeText('P48112730001');
  showToast('订单号已复制');
};

// 获取订单列表
const fetchOrderDetail = async (orderId) => {
  try {
    // loading.value = true;
    // console.log('111', orderId);
    //订单表
    const retOrder = await findOrderByOrderId(orderId);
    order.value = retOrder
    // console.log(order.value.status);

    //订单详情表
    const retOrderDetail = await getDetailsByOrderId(orderId);    
    orderDetail.value = retOrderDetail;

    //服务表
    // console.log('bb',order.value.serviceId);
    const retService = await getServiceById(order.value.serviceId);
    service.value = retService

    //分类表
    const retCategory = await getCategoryById(orderDetail.value[0].categoryId);
    category.value = retCategory

    //地址表
    const retAddress = await getAddressByAddressId(orderDetail.value[0].addressId)
    address.value = retAddress

    // console.log('order:',order.value);
    // console.log('orderDetail:',orderDetail.value);
    // console.log('service:',service.value);
    // console.log('category:',category.value);
    // console.log('address:',address.value);
  } catch (err) {
    console.error('获取订单失败:', err);
    err.value = '加载订单失败，请重试';
    showToast({
      type: 'fail',
      message: '加载失败',
      duration: 1500,
    });
  } finally {
    // loading.value = false;
  }
};

const handleCancel = (orderId) => {
  router.push({
    name: 'cancelOrder',
    query: { orderId }
  });
};

const handleModify = (orderId) => {
  showToast('修改订单功能');
  // 实际修改订单逻辑
  const id = unref(orderId) // 使用unref解包
  router.push({
    name: 'modifyOrder',
    query: { id }
  });
};

// 初始化加载
onMounted(() => {
  orderId.value = route.query.orderId; // 获取参数
  // console.log('接收到的订单ID:', orderId.value);
  fetchOrderDetail(orderId.value);
});

</script>

<style scoped>
.order-detail-container {
  padding-bottom: 60px;
  background-color: #f7f8fa;
  min-height: 100vh;
}

.order-status {
  background: white;
  padding: 16px;
  margin-bottom: 10px;
}

.status-tip {
  margin: 16px 0;
  text-align: center;
}

.status-tip .title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
}

.status-tip .desc {
  font-size: 14px;
  color: #969799;
}

.countdown {
  text-align: center;
  font-size: 14px;
  color: #323233;
}

.countdown .time {
  color: #ee0a24;
  font-weight: bold;
}

.order-info {
  margin-bottom: 10px;
}

.service-detail {
  margin-bottom: 10px;
}

.service-item {
  padding: 8px 16px;
}

.guarantee-tag {
  margin: 8px 0;
}

.guarantee-tip {
  font-size: 12px;
  color: #969799;
}

.guarantee-card {
  background: white;
  padding: 16px;
  margin-bottom: 10px;
}

.guarantee-card .header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.guarantee-card .detail-link {
  color: #1989fa;
}

.guarantee-card .tip {
  font-size: 14px;
  color: #969799;
}

.assistant-card {
  background: white;
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.assistant-card .left {
  display: flex;
  align-items: center;
}

.assistant-card .text {
  margin-left: 10px;
}

.assistant-card .title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 4px;
}

.assistant-card .desc {
  font-size: 12px;
  color: #969799;
}

.assistant-card .right {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.action-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  padding: 10px 16px;
  background: white;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.action-buttons .cancel-btn {
  flex: 1;
  margin-right: 10px;
  border-radius: 30px !important; /* 椭圆形状（数值越大越椭圆） */
}

.action-buttons .modify-btn {
  flex: 1;
  border-radius: 30px !important; /* 椭圆形状（数值越大越椭圆） */
}

/* 修改折叠面板标题样式 */
.service-detail :deep(.van-collapse-item__title) {
  font-size: 14px;
  /* 字体小一点 */
  color: #969799;
  /* 颜色淡一点 */
  text-align: left;
  /* 靠左对齐 */
  padding-left: 16px;
  /* 增加左边距 */
}

/* 自定义单元格样式 */
.custom-cell {
  padding: 10px 16px;
}

.custom-cell :deep(.van-cell__title) {
  font-size: 12px;
  color: #969799;
  /* 标题淡色 */
  text-align: left;
  flex: none;
  /* 防止标题过长挤压值 */
  width: 100px;
  /* 固定标题宽度 */
}

.custom-cell :deep(.van-cell__value) {
  font-size: 12px;
  /* 和标题一样大小 */
  color: #323233;
  /* 颜色更深更明显 */
  text-align: right;
  /* 靠右对齐 */
  flex: 1;
  /* 占据剩余空间 */
}

.icon-with-text {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px; /* 图标和文字的间距 */
}
.text {
  font-size: 12px;
  color: #666;
}

.action-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  border-top: 1px solid #f5f5f5;
}

.icon-with-text {
  display: flex;
  align-items: center;
  gap: 5px;
}

.text {
  font-size: 12px;
  color: #666;
}

.button-group {
  display: flex;
  gap: 8px; /* 调整按钮间距 */
}
</style>